﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Core;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace CustomMVCFilterDemo.Filters
{
    public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            string LogLine = "";

            var ExMessage = filterContext.Exception.Message;
            var ExType = filterContext.Exception.GetType();
            var ExName = ExType.ToString();

            if (ExType == typeof(EntitySqlException))
                NotifyHelpDesk(ExMessage);
            else
                NotifyDevTeam(ExMessage);

            var RtData = filterContext.RouteData;
            var ControllerClassName = RtData.Values["controller"];
            var ActionMethodName = RtData.Values["action"];

            var MethodName = GetCurrentMethod().Name;

            LogLine =
                String.Format("Logging MethodName={0}; Exception Message={1}; ControllerClass={2};  ActionMethod={3}",
                    MethodName, ExMessage, ControllerClassName, ActionMethodName);
            WriteLog(LogLine);
        }

        private void NotifyHelpDesk(string Msg)
        {

            var MethodName = GetCurrentMethod().Name;
            WriteLog(String.Format("Logging MethodName={0}; Exception Message={1}", MethodName, Msg));
        }

        private MethodBase GetCurrentMethod()
        {
            return MethodBase.GetCurrentMethod();
        }

        private void NotifyDevTeam(string Msg)
        {

            var MethodName = GetCurrentMethod().Name;
            WriteLog(String.Format("Logging MethodName={0}; Exception Message={1}", MethodName, Msg));
        }

        public void WriteLog(string Msg)
        {
            var sw = new StreamWriter(GetAssemblyFolderLocation(this.GetType()) + @"\ExceptionLog.txt", true);
            sw.WriteLine(DateTime.Now.ToString() + ": " + Msg);
            sw.Close();
        }

        public static string GetAssemblyFolderLocation(Type type)
        {
            string fullPath = Assembly.GetAssembly(type).Location;
            return Path.GetDirectoryName(fullPath);
        }
    }
}